/*
  假RS485(uno 0,1脚) 与软串口(10,11脚) 之间的互传通讯。本程序可以作为今后串口Modbus调试的基础（通过软串口观察到底收到了什么） 
*/

#include <ArduinoRS485.h> // ArduinoModbus depends on the ArduinoRS485 library
#include <ArduinoModbus.h>
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10,11); //RX,TX


const int numCoils = 1;
const int numDiscreteInputs = 1;
const int numHoldingRegisters = 1;
const int numInputRegisters = 1;

void setup() {
  mySerial.begin(9600);
  
  Serial.begin(9600);
  while (!Serial);

  Serial.println("Modbus RTU Server Kitchen Sink");

  // start the Modbus RTU server, with (slave) id 01
  if (!ModbusRTUServer.begin(01, 9600)) {
    Serial.println("Failed to start Modbus RTU Server!");
    while (1);
  }

//  // configure coils at address 0x00
//  ModbusRTUServer.configureCoils(0x00, numCoils);
//
//  // configure discrete inputs at address 0x00
//  ModbusRTUServer.configureDiscreteInputs(0x00, numDiscreteInputs);

  // configure holding registers at address 0x00
  ModbusRTUServer.configureHoldingRegisters(0x00, numHoldingRegisters);

  // configure input registers at address 0x00
  ModbusRTUServer.configureInputRegisters(0x00, numInputRegisters);
}

void loop() {
  // poll for Modbus RTU requests
  ModbusRTUServer.poll();

//  // map the coil values to the discrete input values
//  for (int i = 0; i < numCoils; i++) {
//    int coilValue = ModbusRTUServer.coilRead(i);
//
//    ModbusRTUServer.discreteInputWrite(i, coilValue);
//  }

  // 这段代码把上位机qt_modbus写给下位机保持寄存器的数据读出来，然后转给输入寄存器，然后再读出来。进测试此代码完全能够运行。
  for (int i = 0; i < numHoldingRegisters; i++) {
    long holdingRegisterValue = ModbusRTUServer.holdingRegisterRead(i);

    ModbusRTUServer.inputRegisterWrite(i, holdingRegisterValue);
//    mySerial.println(holdingRegisterValue);
  }
}
